package com.lw.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lw.ssm.cache.StudentCatch;
import com.lw.ssm.event.StudentEvent;
import com.lw.ssm.exceptions.MyBaseException;
import com.lw.ssm.mapper.StudentMapper;
import com.lw.ssm.pojo.Student;
import com.lw.ssm.service.StudentService;
import com.lw.ssm.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/10 10:10
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

    private StudentMapper studentMapper;

    private StudentCatch studentCatch;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Autowired
    public void setStudentCatch(StudentCatch studentCatch) {
        this.studentCatch = studentCatch;
    }

    @Override
    public Student findById(Long id) {
        return studentMapper.findById(id);
    }

    @Override
    public PageInfo<Student> findAll(int pageNum, int pageSize) {

        PageHelper.startPage(pageNum,pageSize);
//        List<Student> studentList = studentMapper.findAll();
//        PageInfo<Student> studentPageInfo = new PageInfo<>(studentList);
        List<Student> studentList = studentCatch.getAllData();
        List<Student> collect = studentList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<Student> studentPageInfo = new PageInfo<>(collect);
        studentPageInfo.setTotal(studentList.size());//设置一次总长度
        return studentPageInfo;
    }

    @Override
    public void addStudent(Student student) {
        Assert.isTrue(!student.isEmpty(),()->{
            throw new MyBaseException("传递数据不能为空", ResultCode.DATA_EMPTY);
        });
        studentMapper.addStudent(student);
        context.publishEvent(new StudentEvent());
    }

    @Override
    public void updateById(Student student) {
        studentMapper.updateById(student);
        context.publishEvent(new StudentEvent());
    }

    @Override
    public void deleteById(Long id) {
        studentMapper.deleteById(id);
        context.publishEvent(new StudentEvent());
    }
}
